"""
@author: zrp
@file: 2023-12-04-下载图片作业.py
@time: 2023/12/4 15:59
"""
import logging
import sys
logging.basicConfig(level=logging.DEBUG,stream=sys.stdout)
import requests
from bs4 import BeautifulSoup
import os

#获取文本文件
def result(url):
    try:
        response=requests.get(url, verify=False)#绕过安全验证
        response.raise_for_status()
        response.encoding=response.apparent_encoding
        logging.info(response.text)
        return response.text
    except:
        return False


#获取二进制文件
def result_img(url):
    try:
        response=requests.get(url, verify=False)#绕过安全验证
        response.raise_for_status()
        response.encoding=response.apparent_encoding
        return response.content
    except:
        return False

#主函数
path="./web_imgs"
if not  os.path.exists(path):
    os.mkdir(path)
url="https://www.sanchuangedu.cn/"
data1=result(url)
soup=BeautifulSoup(data1,"lxml")
pics=soup.find_all("img")
for i in  pics:
    pic_url=url+i["src"]
    logging.info(pics)
    filename = f"{path}/{i['src']}"
    with open(filename,"wb") as fp:
        fp.write(result_img(pic_url))
    print(f"{pic_url}保存成功！")
